import { sleep } from '@gnlab/utils'
import dayjs from 'dayjs'

export { default as random } from 'lodash/random'
export { sleep }

export function log(message: string, ...styles: string[]) {
  console.log(`[${dayjs().format('HH:mm:ss.SSS')}] ${message}`, ...styles)
}

export function formatMs(ms: number) {
  ms = Math.round(ms)
  if (ms > 1000) {
    return `${ms / 1000}s`
  }
  return `${ms}ms`
}

let nextId = 1
export function run(title: string, testcase: () => void) {
  repeatRun(title, testcase, 1)
}
export function repeatRun(title: string, testcase: () => void, repeat = 3) {
  const id = nextId++
  log(`开始#${id} %c${title}`, 'color: green')

  const costs: number[] = []
  let times = 1
  while (times++ <= repeat) {
    const start = Date.now()
    testcase()
    const end = Date.now()
    costs.push(end - start)
  }

  // 如果 repeat 次数少，显示每一次的 cost
  // 如果次数多，显示 cost 平均值
  const totalCost = costs.reduce((a, b) => a + b, 0)
  const costsText =
    repeat <= 5
      ? `costs: %c${costs.map(formatMs).join('、')}`
      : `avg: %c${formatMs(totalCost / repeat)}`

  log(
    `结束#${id} ${costsText} %ctotal: %c${formatMs(totalCost)}`,
    'color: red',
    'color: black',
    'color: red',
  )
  console.log('')
}
